package win.larryzeal.spring.jms.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.time.Instant;

/**
 * Created by 张少昆 on 2017/8/4 0004.
 */
@Service
public class JmsProducerService {
    @Autowired
    private JmsTemplate jmsTemplate;

    // @Value( "${activemq.topic.test}" )
    // private String topic;

    @Resource( name = "topic-test" )
    private Destination topic;

    /**
     * 发送到默认destination
     */
    public void sendMessage(){
        for(int i = 0; i < 100; i++){
            jmsTemplate.convertAndSend("msg[" + i + "] @" + Instant.now().toString()); //default destination
        }
    }

    /**
     * 发送到指定destination
     */
    public void sendMessage2(){
        for(int i = 0; i < 20; i++){
            int finalI = i;
            jmsTemplate.send(topic, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException{
                    // session.createTopic()
                    return session.createTextMessage("topic[" + topic + "] msg[" + finalI + "] @" + Instant.now().toString());
                }
            });
        }
        System.out.println("topic["+topic+"] 消息发送完毕");
    }

}
